package com.oa.controller;

import java.io.IOException;


import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;


import com.oa.dao.PublicNoticeDao;
import com.oa.entity.PublicNotice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
/*
* 通知-群发
* */


@ServerEndpoint("/mySocket/{userId}")
@Component
public class NoticeWebScoketController {

    /**静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,NoticeWebScoketController> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId="";

    /**
     * @Description 当客户端链接时，调用该方法
     * @return void
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {

        this.session = session;
        this.userId=userId;
        if (webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
            //加入set中
            System.out.println("有新链接加入："+userId+"，在线人数："+getOnlineCount());
        }else {
            webSocketMap.put(userId,this);
            //加入set中
            addOnlineCount();
            //在线数加1
            System.out.println("有新链接加入："+userId+"，在线人数："+getOnlineCount());
        }



    }

    /**
     * @Description 当链接断开时，调用该方法
     * @return void
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }

        System.out.println("有链接断开："+userId+"，在线人数："+getOnlineCount());
    }

    /**
     * @Description 当发送异常时，调用该方法
     * @return void
     */
    @OnError
    public void onError(Throwable throwable) {
        System.out.println("error");
    }

    /**
     * @Description 当接收到客户端信息时，调用该方法
     * @return void
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("用户："+userId+"发送消息："+message);
        try {
            sendMessage(message);
            System.out.println("用户："+userId+"链接成功");
        } catch (IOException e) {
            System.out.println("用户："+userId+"网络异常");
        }
        //可以群发消息
        //消息保存到数据库、redis
       /* if(StringUtils.isNotBlank(message)){
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("fromUserId",this.userId);
                String toUserId=jsonObject.getString("toUserId");
                //传送给对应toUserId用户的websocket
                if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
                }else{

                    System.out.println("请求的userId"+toUserId+"不在改服务器上");
                    //否则不在这个服务器上，发送到mysql或者redis
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }*/
    }


    /**
     * @Description 发送处理信息
     * @return void
     */
    public void sendAll(String message) {
        System.out.println(message);
        //遍历所有在线用户
        if (!webSocketMap.equals(userId)){
        for (String key : webSocketMap.keySet()) {
            try {
                sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
       /* for(Entry<String, Session> user:map.entrySet()) {
            //获取集合中每个session用户
            Session se = user.getValue();
            //给每个用户都发送信息
            se.getAsyncRemote().sendText(msg);
        }*/
    }
 }





    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        NoticeWebScoketController.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        NoticeWebScoketController.onlineCount--;
    }


}
